package com.umerclass;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.multidex.MultiDex;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.lzx.starrysky.StarrySky;
import com.lzx.starrysky.StarrySkyBuilder;
import com.lzx.starrysky.StarrySkyConfig;
import com.lzx.starrysky.delayaction.Valid;
import com.lzx.starrysky.provider.SongInfo;
import com.lzx.starrysky.registry.StarrySkyRegistry;
import com.qw.soul.permission.SoulPermission;
import com.qw.soul.permission.bean.Permission;
import com.qw.soul.permission.bean.Permissions;
import com.qw.soul.permission.callbcak.CheckRequestPermissionsListener;
import com.umerclass.bean.anmo.UserOtherBean;
import com.umerclass.bean.user.UserInfo;
import com.umerclass.frame.logger.AndroidLogAdapter;
import com.umerclass.frame.logger.FormatStrategy;
import com.umerclass.frame.logger.Logger;
import com.umerclass.frame.logger.PrettyFormatStrategy;
import com.umerclass.ui.home.view.GlideLoader;
import com.umerclass.utils.MusicRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * App application
 * @author jack
 */

public class AppDroid extends Application {

    private static AppDroid instance;
    private List<Activity> activities = new ArrayList<Activity>();
    private UserInfo mUserInfo;
    private UserOtherBean userOtherBean;

    @Override
    public void onCreate() {
        super.onCreate();
        //全局Application
        instance = this;
        Fresco.initialize(this);
        //图片压缩框架初始化
        //Tiny.getInstance().init(this);

        /**
         *日志打印初始化
         */
        //Initialize初始化
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(true)  // (Optional) Whether to show thread info or not. Default true
                .methodCount(2)         // (Optional) How many method line to show. Default 2
                .methodOffset(3)        // (Optional) Skips some method invokes in stack trace. Default 5
//        .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat
                .tag("Staff")   // (Optional) Custom tag for each log. Default PRETTY_LOGGER
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
        //todo
        Logger.d("message");
        Logger.w("no thread info and only 1 method");
        Logger.i("no thread info and method info");
        Logger.e("Custom tag for only one use");//错误信息 红色的
        Logger.json("{ \"key\": 3, \"value\": something}");
        Logger.d(Arrays.asList("foo", "bar"));
        Map<String, String> map = new HashMap<>();
        map.put("key", "value");
        map.put("key1", "value2");
        Logger.d(map);
        //================================================================================
        //StarrySky.init(this);
        StarrySky.init(this, new TestConfig());
    }

    public static AppDroid getInstance() {
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
        //MultiDex.install(this);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    /**
     * 新建了一个activity
     * @param activity
     */
    public void addActivity(Activity activity){
        if(activities!=null && !activities.contains(activity)){
            activities.add(activity);
        }
    }

    public void clearStack() {
        List<Activity> activityStack = activities;
        for (int i = activityStack.size() - 1; i >= 0; i--) {
            Activity activity = activityStack.get(i);
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
        activityStack.clear();
    }

    /**
     *  结束指定的Activity
     * @param activity-
     */
    public void finishActivity(Activity activity){
        if (activity!=null) {
            this.activities.remove(activity);
            activity.finish();
        }
    }

    /**
     *  结束指定的Activity
     */
    public void finishAllActivitys(){
        for(Activity a : activities) {
            if (a!=null) {
                a.finish();
            }
        }
    }

    /**
     * 应用退出，结束所有的activity
     */
    public void exitClient(){
        for(Activity activity : activities) {
            if (activity!=null) {
                activity.finish();
            }
        }
        System.exit(0);
    }

    public UserInfo getUserInfo() {
        return mUserInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        mUserInfo = userInfo;
    }

    public UserOtherBean getUserOtherBean() {
        return userOtherBean;
    }

    public void setUserOtherBean(UserOtherBean userOtherBean) {
        this.userOtherBean = userOtherBean;
    }


    private static class TestConfig extends StarrySkyConfig {

        @Override
        public void applyOptions(@NonNull Context context, @NonNull StarrySkyBuilder builder) {
            super.applyOptions(context, builder);
            builder.setOpenNotification(false);
            builder.setOpenCache(true);
            String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/UmerXian/";
            builder.setCacheDestFileDir(destFileDir);
        }

        /**
         * 添加组件
         */
        @Override
        public void applyStarrySkyRegistry(@NonNull Context context, StarrySkyRegistry registry) {
            super.applyStarrySkyRegistry(context, registry);
            registry.appendValidRegistry(new RequestSongInfoValid(context));
            registry.registryImageLoader(new GlideLoader());
        }
    }

    public static class RequestSongInfoValid implements Valid {
        private MusicRequest mMusicRequest;
        private Context mContext;

        RequestSongInfoValid(Context context) {
            mContext = context;
            mMusicRequest = new MusicRequest();
        }

        @Override
        public void doValid(SongInfo songInfo, ValidCallback callback) {
            SoulPermission.getInstance().checkAndRequestPermissions(
                    Permissions.build(
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    new CheckRequestPermissionsListener() {
                        @Override
                        public void onAllPermissionOk(Permission[] allPermissions) {
                            if (TextUtils.isEmpty(songInfo.getSongUrl())) {
                                mMusicRequest.getSongInfoDetail(songInfo.getSongId(), songUrl -> {
                                    songInfo.setSongUrl(songUrl); //给songInfo设置Url
                                    callback.finishValid();
                                });
                            } else {
                                callback.doActionDirect();
                            }
                        }

                        @Override
                        public void onPermissionDenied(Permission[] refusedPermissions) {
                            Toast.makeText(mContext, "没有权限，播放失败", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }
}